<?php

namespace app\api\controller;

use app\common\model\AdminModel;
use think\Controller;
use think\Request;
use Firebase\JWT\JWT;
use think\Db;
class Login extends Cross
{
    //PC端后台登录
   public function login(Request $request){
       $username = $request->param('username');
       $password = $request->param('password');
       $admin = new AdminModel();
       $info = $admin->where('username',$username)->find();
       if (!$info){
           return json(['code'=>-1,'msg'=>'账户不存在']);
       }
       if ($info['password'] != md5($password)){
           return json(['code'=>-1,'msg'=>'密码错误']);

       }
//       jwt json
       $jwt = new JWT();
       $key = 'api123456';
       $payload = array(
           'iss' => "http://www.api.io",
           'aud' => "http://www.api.io",
           'iat' => time(),
           'nbf' => time(),
           'aid' => $info['id']
       );
       $token = $jwt::encode($payload, $key);
       return json(['code'=>1,'msg'=>'登录成功','token'=>$token]);
   }
    //APP登录
    /**
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
   public function appLogin(Request $request){
       $username = $request->param('username');
       $password = $request->param('password');
       $field = "id,username, password, head_picture, nick_name";
       $user_info = Db::name("user")->field($field)->find();
       if (!empty($user_info)){
           if (empty($user_info['nick_name'])){
               $user_info['nick_name'] = '123456';
           }
           if (empty($user_info['head_picture'])){
               $user_info['head_picture'] = 'http://106.55.6.120/staticResources/CcdVQP.png';
           }
           return json(['code'=>200,'message'=>'登录成功','result'=>$user_info]);
       }else{
           return json(['code'=>-1,'message'=>'登录失败']);
       }
   }
   //APP注册
    public function register(Request $request)
    {
        $data['username'] = $request->param('username');
        $data['password'] = $request->param('password');
        $data['create_time'] = time();
        if (Db::name('user')->insert($data)){
            return json(['code'=>200,'message'=>'注册成功','result'=>null]);
        }else{
            return json(['code'=>-1,'message'=>'注册失败']);
        }
    }

}
